package com.atguigu.tingshu.album.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.TingShuException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioConstantProperties properties;

    @Override
    public String fileUpload(MultipartFile file) {
        try{
            BufferedImage read = ImageIO.read(file.getInputStream());
            if(read == null){
                throw new TingShuException(400,"图片非法");
            }
            String folderName = "/" + DateUtil.today() + "/";
            String fileName = IdUtil.randomUUID();
            String extName = FileUtil.extName(file.getOriginalFilename());
            //拼接
            String objectName = folderName + fileName + "." + extName;
            //上传到minio
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(properties.getBucketName()).object(objectName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            String filUrl = properties.getEndpointUrl() + "/" + properties.getBucketName() + objectName;
            log.info("上传图片成功，图片地址为：{}",filUrl);
            //返回结果
            return filUrl;

        }catch (Exception e){
           log.error("专辑上传图片异常,{}",e);
            throw new TingShuException(400,"专辑上传图片异常");
        }
    }
}
